﻿using System;
using System.Text;
using System.IO;
/// <summary>
/// This is a class to handle logging Linq to Sql output to a file.
/// To use it you can edit the GenericRepository 
/// </summary>
public class FileLogger : TextWriter
{
    public string FileName {get; set;}

    public FileLogger(string fileName): this(fileName, false)
    {

    }

    public FileLogger(string fileName, bool deleteExistingLog)
    {
        FileName = fileName;
        if(deleteExistingLog)
            File.Delete(fileName);
    }

    public override void Write(char value)
    {
        Log(value.ToString());
    }

    public override void Write(string value)
    {
        if (value != null)
        {
            Log(value);
        }
    }

    public override void Write(char[] buffer, int index, int count)
    {
        if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count)
        {
            base.Write(buffer, index, count); 
        }
        Log(new string(buffer, index, count));
    }
    protected void Log(string message)
    {
        if(string.IsNullOrEmpty(FileName))
            throw new ArgumentException("You must set the FileName property before using the class");

        StreamWriter sw;
        try
        {
            if (!File.Exists(FileName))
                sw = File.CreateText(FileName);
            else
                sw = File.AppendText(FileName);

            sw.WriteLine(message);
            sw.Close();
        }
        catch (Exception)
        {
            //We don't want the logging screwing up the app, so swallow the exception
        }
    }

    public override Encoding Encoding
    {
        get
        {
            return new UnicodeEncoding(false, false);
        }
    }
}
